﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using Newtonsoft.Json;

namespace WpfBeyond
{   
    class Common
    {
        public static List<audio_device_name> audio_device_list = new List<audio_device_name>();
        public static List<DateTimeRange> sel_dates = new List<DateTimeRange>();
        public static List<PlayInfo> sel_playlist = new List<PlayInfo>();

        public static bool reflash_device = false;//设备状态刷新标志
        public static bool reflash_task = false;//任务状态刷新标志        
              
        public delegate void LoadingHandler(bool Active);
        public static event LoadingHandler LoadingCallBack;

        public static void ShowMessage(string title, string msg)
        {
            MetroWindow metroWindow = Application.Current.MainWindow as MetroWindow;
            metroWindow.ShowMessageAsync(title, msg);
         
        }

        public static void ShowLoading(bool Active)
        {
            if (LoadingCallBack != null)
            {
                LoadingCallBack(Active);
            }
        }

        public static void SaveJson(string fileName, object? value)
        {
            if (value == null) return;

            //保存设备信息
            JsonSerializer serializer = new JsonSerializer();
            serializer.NullValueHandling = NullValueHandling.Ignore;

            using (StreamWriter sw = new StreamWriter(fileName))
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                serializer.Serialize(writer, value);
            }
        }
        
        public static List<TaskInfo> LoadTaskJson()
        {
            try
            {
                using (StreamReader sr = new StreamReader(LocalSetting.taskinfo_JsonFileName))
                {
                    string output = sr.ReadToEnd();
                    return JsonConvert.DeserializeObject<List<TaskInfo>>(output);
                }
            }
            catch (Exception ex)
            {
                LogHelp.Error(ex.ToString());
            }
            return null;
        }

        public static SettingItem LoadSettingJson()
        {
            try
            {
                if( Directory.Exists(LocalSetting.history_path) == false)
                {
                    Directory.CreateDirectory(LocalSetting.history_path);
                }

                using (StreamReader sr = new StreamReader(LocalSetting.setting_JsonFileName))
                {
                    string output = sr.ReadToEnd();
                    return JsonConvert.DeserializeObject<SettingItem>(output);
                }
            }
            catch (Exception ex)
            {
                LogHelp.Error(ex.ToString());
            }
            return null;
        }

        public static List<Device> LoadDevicesJson()
        {
            try
            {
                using (StreamReader sr = new StreamReader(LocalSetting.devices_JsonFileName))
                {
                    string output = sr.ReadToEnd();
                    return JsonConvert.DeserializeObject<List<Device>>(output);
                }
            }
            catch (Exception ex)
            {
                LogHelp.Error(ex.ToString());
            }
            return null;
        }

        public static List<TaskInfo> LoadHistoryJson()
        {
            try
            {
                using (StreamReader sr = new StreamReader(LocalSetting.History_JsonFileName))
                {
                    string output = sr.ReadToEnd();
                    return JsonConvert.DeserializeObject<List<TaskInfo>>(output);
                }
            }
            catch (Exception ex)
            {
                LogHelp.Error(ex.ToString());
            }
            return null;
        }

        public static string BCD2STR(byte[] b, int len)
        {
            int i = 0;
            StringBuilder sb = new StringBuilder();

            sb.Remove(0, sb.Length);
            for (i = 0; i < len; i++)
            {
                sb.Append(b[i].ToString("X2"));
            }

            return sb.ToString();
        }

        public static string BCD2IP(byte[] b, int len)
        {
            int i = 0;
            StringBuilder sb = new StringBuilder();

            sb.Remove(0, sb.Length);
            for (i = 0; i < len; i++)
            {
                sb.Append(b[i].ToString());
                if (i != len - 1)
                {
                    sb.Append(".");
                }
            }

            return sb.ToString();
        }

        public static Byte[] IP2BCD(string ip)
        {
            try
            {
                string[] num = ip.Split(".");
                Byte[] aryTemp = new Byte[4];

                //IP地址位数不对
                if (num.Length != 4) return aryTemp;


                for (int i = 0; i < num.Length; i++)
                {
                    aryTemp[i] = Convert.ToByte(num[i]);
                }
                return aryTemp;//高位在前 
            }
            catch
            { return null; }

        }

        /// <summary>
        /// 字符串转换为BCD编码
        /// </summary>
        /// <param name="strTemp">转换字符串</param>
        /// <returns>BCD编码</returns>
        public static Byte[] STR2BCD(string strTemp)
        {
            string tmpstr = "0123456789ABCDEF";

            try
            {
                if (Convert.ToBoolean(strTemp.Length & 1))//数字的二进制码最后1位是1则为奇数 
                {
                    strTemp = "0" + strTemp;//数位为奇数时前面补0 
                }
                Byte[] aryTemp = new Byte[strTemp.Length / 2];
                for (int i = 0; i < (strTemp.Length / 2); i++)
                {
                    byte high = (byte)tmpstr.IndexOf(Char.ToUpper(strTemp[i * 2]));
                    byte low = (byte)tmpstr.IndexOf(Char.ToUpper(strTemp[i * 2 + 1]));

                    aryTemp[i] = (Byte)((high << 4) | low);
                }
                return aryTemp;//高位在前 
            }
            catch
            { return null; }
        }

        public static short flowid = 0;
        public static short ebmid_flowid()
        {
            //先查找当前运行任务中的最新FLOWID      
            if (TaskFactory.list != null && TaskFactory.list.Count > 0)
            {
                flowid = short.Parse(TaskFactory.list[TaskFactory.list.Count - 1].Ebmid_str.Substring(32, 4));
            }
            else
            {
                List<TaskInfo> list = new List<TaskInfo>();
                DateTime dt = DateTime.Now;

                string path = @"history/" + dt.ToShortDateString() + ".json";

                try
                {
                    using (StreamReader sr = new StreamReader(path))
                    {
                        string output = sr.ReadToEnd();
                        list = JsonConvert.DeserializeObject<List<TaskInfo>>(output);
                        if (list != null && list.Count > 0)
                        {
                            //18字节数据 36位数字
                            flowid = short.Parse(list[0].Ebmid_str.Substring(32, 4));
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelp.Error(ex.ToString());
                }
            }

            if (flowid >= 9999)
            {
                flowid = 0;
            }
            flowid++;

            return flowid;
        }


    }
}
